<template>
  <view class="profile-edit-container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <view class="nav-left" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="nav-center">
        <text class="nav-title">编辑资料</text>
      </view>
    </view>

    <!-- 表单内容 -->
    <view class="form-content">
      <!-- 头像上传 -->
      <view class="form-section">
        <text class="section-title">头像</text>
        
        <view class="avatar-upload">
          <view class="avatar-preview" @click="chooseAvatar">
            <!-- 已有头像 -->
            <image 
              v-if="formData.avatar" 
              :src="formData.avatar" 
              mode="aspectFill" 
              class="avatar-img"
              @error="onAvatarError"
              @load="onAvatarLoad"
            />
            <!-- 没有头像 -->
            <view v-else class="avatar-placeholder">
              <text class="placeholder-icon">📷</text>
              <text class="placeholder-text">点击上传头像</text>
            </view>
            
            <!-- 上传中遮罩 -->
            <view v-if="uploadProgress > 0 && uploadProgress < 100" class="upload-mask">
              <text class="upload-mask-text">{{ uploadProgress }}%</text>
            </view>
          </view>
          
          <text class="upload-hint">支持 jpg、png、gif，最大 5MB</text>
        </view>
      </view>

      <!-- 账号信息（不可编辑） -->
      <view class="form-section">
        <text class="section-title">账号信息</text>
        
        <view class="form-item disabled">
          <text class="item-label">用户名</text>
          <input 
            class="item-input" 
            v-model="formData.username" 
            disabled
            placeholder="加载中..."
          />
        </view>

        <view class="form-item disabled">
          <text class="item-label">邮箱</text>
          <input 
            class="item-input" 
            v-model="formData.email" 
            disabled
            placeholder="加载中..."
          />
          <text class="item-tip">如需修改邮箱，请前往"修改邮箱"页面</text>
        </view>
      </view>

      <!-- 个人信息（可编辑） -->
      <view class="form-section">
        <text class="section-title">个人信息</text>
        
        <view class="form-item">
          <text class="item-label">真实姓名</text>
          <input 
            class="item-input" 
            v-model="formData.realName" 
            placeholder="请输入真实姓名（2-20个字符）"
            maxlength="20"
          />
        </view>

        <view class="form-item">
          <text class="item-label">手机号</text>
          <input 
            class="item-input" 
            type="number"
            v-model="formData.phone" 
            placeholder="请输入手机号"
            maxlength="11"
          />
        </view>

        <view class="form-item">
          <text class="item-label">性别</text>
          <view class="gender-selector">
            <view 
              class="gender-option" 
              :class="{ active: formData.gender === 'male' }"
              @click="selectGender('male')"
            >
              <text class="gender-icon">👨</text>
              <text class="gender-text">男</text>
            </view>
            <view 
              class="gender-option" 
              :class="{ active: formData.gender === 'female' }"
              @click="selectGender('female')"
            >
              <text class="gender-icon">👩</text>
              <text class="gender-text">女</text>
            </view>
            <view 
              class="gender-option" 
              :class="{ active: formData.gender === 'secret' }"
              @click="selectGender('secret')"
            >
              <text class="gender-icon">🤐</text>
              <text class="gender-text">保密</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="action-buttons">
      <button class="save-btn" @click="handleSave">保存修改</button>
    </view>
  </view>
</template>

<script>
import authService from '../../services/auth.js'
import { smartBack } from '../../utils/navigation.js'

export default {
  data() {
    return {
      statusBarHeight: 0,
      
      // 表单数据
      formData: {
        username: '',
        email: '',
        realName: '',
        phone: '',
        gender: 'secret',
        avatar: ''
      },
      
      // 原始数据（用于判断是否有修改）
      originalData: {},
      
      // 上传进度
      uploadProgress: 0
    }
  },
  
  onLoad() {
    this.getStatusBarHeight()
    this.loadUserProfile()
  },
  
  methods: {
    // 获取状态栏高度
    getStatusBarHeight() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 20
      document.documentElement.style.setProperty('--status-bar-height', this.statusBarHeight + 'px')
    },

    // 加载用户资料
    async loadUserProfile() {
      try {
        uni.showLoading({ title: '加载中...' })
        
        const response = await authService.getProfile()
        const userData = response.data
        
        // 填充表单
        this.formData = {
          username: userData.username || '',
          email: userData.email || '',
          realName: userData.realName || '',
          phone: userData.phone || '',
          gender: userData.gender || 'secret',
          avatar: userData.avatar || ''
        }
        
        // 保存原始数据
        this.originalData = { ...this.formData }
        
        uni.hideLoading()
      } catch (error) {
        uni.hideLoading()
        console.error('加载用户资料失败:', error)
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      }
    },

    // 选择头像
    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0]
          
          // 检查文件大小（5MB = 5 * 1024 * 1024 bytes）
          uni.getFileInfo({
            filePath: tempFilePath,
            success: (fileInfo) => {
              if (fileInfo.size > 5 * 1024 * 1024) {
                uni.showToast({
                  title: '图片大小不能超过5MB',
                  icon: 'none'
                })
                return
              }
              
              // 上传图片
              this.uploadAvatar(tempFilePath)
            },
            fail: () => {
              // 如果获取文件信息失败，直接上传
              this.uploadAvatar(tempFilePath)
            }
          })
        },
        fail: (error) => {
          console.error('选择图片失败:', error)
        }
      })
    },
    
    // 上传头像到服务器
    uploadAvatar(filePath) {
      const token = uni.getStorageSync('jwt_token')
      if (!token) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }
      
      // 重置上传进度
      this.uploadProgress = 0
      
      // 上传文件
      const uploadTask = uni.uploadFile({
        url: 'http://localhost:8080/api/v1/upload/image',
        filePath: filePath,
        name: 'file',
        header: {
          'Authorization': `Bearer ${token}`
        },
        success: (uploadRes) => {
          if (uploadRes.statusCode === 200) {
            try {
              const result = JSON.parse(uploadRes.data)
              
              if (result.code === 200 && result.data && result.data.url) {
                // 上传成功，保存图片URL
                this.formData.avatar = result.data.url
                this.uploadProgress = 100
                
                uni.showToast({
                  title: '上传成功',
                  icon: 'success'
                })
                
                // 1秒后清除进度条
                setTimeout(() => {
                  this.uploadProgress = 0
                }, 1000)
              } else {
                throw new Error(result.message || '上传失败')
              }
            } catch (error) {
              console.error('解析响应失败:', error)
              uni.showToast({
                title: '上传失败：' + error.message,
                icon: 'none'
              })
              this.uploadProgress = 0
            }
          } else {
            uni.showToast({
              title: '上传失败：' + uploadRes.statusCode,
              icon: 'none'
            })
            this.uploadProgress = 0
          }
        },
        fail: (error) => {
          console.error('上传失败:', error)
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
          this.uploadProgress = 0
        }
      })
      
      // 监听上传进度
      uploadTask.onProgressUpdate((res) => {
        this.uploadProgress = res.progress
      })
    },
    
    // 头像加载成功
    onAvatarLoad() {
      // 头像加载成功
    },
    
    // 头像加载失败
    onAvatarError(e) {
      console.error('头像加载失败:', this.formData.avatar, e)
      uni.showToast({
        title: '头像加载失败，请检查网络',
        icon: 'none'
      })
    },

    // 选择性别
    selectGender(gender) {
      this.formData.gender = gender
    },

    // 表单验证
    validateForm() {
      // 真实姓名验证
      if (this.formData.realName && this.formData.realName.trim() !== '') {
        if (this.formData.realName.length < 2 || this.formData.realName.length > 20) {
          uni.showToast({
            title: '真实姓名长度必须在2-20个字符之间',
            icon: 'none'
          })
          return false
        }
      }

      // 手机号验证
      if (this.formData.phone && this.formData.phone.trim() !== '') {
        const phoneRegex = /^1[3-9]\d{9}$/
        if (!phoneRegex.test(this.formData.phone)) {
          uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none'
          })
          return false
        }
      }

      return true
    },

    // 检查是否有修改
    hasChanges() {
      return this.formData.realName !== this.originalData.realName ||
             this.formData.phone !== this.originalData.phone ||
             this.formData.gender !== this.originalData.gender ||
             this.formData.avatar !== this.originalData.avatar
    },

    // 保存修改
    async handleSave() {
      // 检查是否有修改
      if (!this.hasChanges()) {
        uni.showToast({
          title: '没有修改任何内容',
          icon: 'none'
        })
        return
      }

      // 表单验证
      if (!this.validateForm()) {
        return
      }

      try {
        uni.showLoading({ title: '保存中...' })

        // 提交数据（只提交可编辑的字段）
        const submitData = {
          realName: this.formData.realName || null,
          phone: this.formData.phone || null,
          gender: this.formData.gender,
          avatar: this.formData.avatar || null
        }

        await authService.updateProfile(submitData)

        uni.hideLoading()
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })

        // 返回上一页
        setTimeout(() => {
          smartBack('/pages/profile/profile')
        }, 1000)

      } catch (error) {
        uni.hideLoading()
        console.error('保存失败:', error)
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        })
      }
    },

    // 返回
    goBack() {
      // 检查是否有未保存的修改
      if (this.hasChanges()) {
        uni.showModal({
          title: '提示',
          content: '您有未保存的修改，确定要离开吗？',
          success: (res) => {
            if (res.confirm) {
              smartBack('/pages/profile/profile')
            }
          }
        })
      } else {
        smartBack('/pages/profile/profile')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.profile-edit-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 180rpx;
}

.status-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 999;
}

// 顶部导航栏
.top-nav {
  position: fixed;
  top: var(--status-bar-height);
  left: 0;
  right: 0;
  height: 88rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
  display: flex;
  align-items: center;
  z-index: 998;
}

.nav-left {
  position: absolute;
  left: 0;
  width: 88rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 36rpx;
  color: #333;
}

.nav-center {
  flex: 1;
  text-align: center;
}

.nav-title {
  font-size: 32rpx;
  font-weight: 700;
  color: #333;
}

// 表单内容
.form-content {
  margin-top: calc(var(--status-bar-height) + 88rpx + 20rpx);
  padding: 20rpx;
}

.form-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  display: block;
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 24rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

// 头像上传
.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20rpx;
}

.avatar-preview {
  width: 200rpx;
  height: 200rpx;
  border-radius: 50%;
  overflow: hidden;
  background: #f5f5f5;
  border: 2rpx dashed #ddd;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
  }
}

.avatar-img {
  width: 100%;
  height: 100%;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
}

.placeholder-icon {
  font-size: 60rpx;
}

.placeholder-text {
  font-size: 22rpx;
  color: #999;
}

.upload-hint {
  font-size: 22rpx;
  color: #999;
  text-align: center;
}

.upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.upload-mask-text {
  font-size: 28rpx;
  color: #fff;
  font-weight: 600;
}

// 上传进度
.upload-progress {
  width: 100%;
  margin-top: 10rpx;
}

.progress-bar {
  width: 100%;
  height: 8rpx;
  background: #f0f0f0;
  border-radius: 4rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #ff8a00, #ffb300);
  border-radius: 4rpx;
  transition: width 0.3s ease;
}

.progress-text {
  display: block;
  text-align: center;
  font-size: 22rpx;
  color: #ff8a00;
  margin-top: 8rpx;
}

// 表单项
.form-item {
  margin-bottom: 32rpx;

  &:last-child {
    margin-bottom: 0;
  }
  
  &.disabled {
    opacity: 0.6;
  }
}

.item-label {
  display: block;
  font-size: 26rpx;
  color: #333;
  margin-bottom: 16rpx;
  font-weight: 500;
}

.item-input {
  width: 100%;
  height: 72rpx;
  padding: 0 20rpx;
  border: 2rpx solid #e1e5e9;
  border-radius: 12rpx;
  font-size: 26rpx;
  background: #fff;
  
  &:disabled {
    background: #f5f5f5;
    color: #999;
  }
}

.item-tip {
  display: block;
  font-size: 22rpx;
  color: #999;
  margin-top: 8rpx;
}

// 性别选择
.gender-selector {
  display: flex;
  gap: 20rpx;
  justify-content: space-between;
}

.gender-option {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 24rpx 16rpx;
  border-radius: 12rpx;
  border: 2rpx solid #e1e5e9;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
  }
  
  &.active {
    border-color: #ff8a00;
    background: linear-gradient(135deg, #fff7ec 0%, #fffaf0 100%);
    
    .gender-icon {
      transform: scale(1.1);
    }
    
    .gender-text {
      color: #ff8a00;
      font-weight: 600;
    }
  }
}

.gender-icon {
  font-size: 40rpx;
  transition: transform 0.3s ease;
}

.gender-text {
  font-size: 24rpx;
  color: #666;
  transition: all 0.3s ease;
}

// 保存按钮
.action-buttons {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid #eee;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.save-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #ff8a00 0%, #ffa726 100%);
  color: #fff;
  border: none;
  border-radius: 16rpx;
  font-size: 28rpx;
  font-weight: 600;
  box-shadow: 0 8rpx 20rpx rgba(255, 138, 0, 0.3);
  
  &:active {
    opacity: 0.9;
    transform: scale(0.98);
  }
}
</style>

